package com.judge.mylibrary;

import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**自定义带删除按钮的EditText
 * Created by xuzhifan on 2016/12/8 0008.
 */

public class DeleteEditLayout extends LinearLayout{
    private EditText mEditText;
    private ImageView mImageView;
    public DeleteEditLayout(Context context) {
        super(context);
    }

    public DeleteEditLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.deleteeditlayout, this, true);
        mEditText = (EditText) findViewById(R.id.et);
        mEditText.addTextChangedListener(mWatcher);
        mEditText.setOnFocusChangeListener(mFocusChangeListener);
        mImageView = (ImageView) findViewById(R.id.iv);
        mImageView.setVisibility(View.GONE);
        mImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditText.setText("");
            }
        });
    }

    public DeleteEditLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 设置edittext的输入提示信息
     * @param strid
     */
    public void setEditTextHint(int strid){
        mEditText.setHint(strid);
    }

    /**
     * 设置edittext输入类型为密码
     */
    public void setPassWordType(){
        mEditText.setInputType( InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

    /**
     * 设置edittext输入类型为电话
     */
    public void setPhoneType(){
        mEditText.setInputType(InputType.TYPE_CLASS_PHONE);
    }
    private OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean focus) {
            if(focus && !TextUtils.isEmpty(mEditText.getText().toString())){//如果获取焦点并且edittext不为空
                mImageView.setVisibility(View.VISIBLE);
            }else{
                mImageView.setVisibility(View.GONE);
            }
        }
    };
    private TextWatcher mWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
              String context = editable.toString();
              if(TextUtils.isEmpty(context)){
                  mImageView.setVisibility(View.GONE);
              }else{
                  mImageView.setVisibility(View.VISIBLE);
              }
        }
    };
}
